package com.itheima.controller;

import com.aliyuncs.exceptions.ClientException;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisConstant;
import com.itheima.entity.Result;
import com.itheima.utils.SMSUtils;
import com.itheima.utils.ValidateCodeUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.concurrent.TimeUnit;

/**
 * 验证码发送
 */
@Api(tags = "ValidateCodeController-验证码发送")
@RestController
@RequestMapping("/validateCode")
@CrossOrigin
public class ValidateCodeController {
    @Autowired
    private RedisTemplate redisTemplate;

    //用户在线预约时发送验证码
    @ApiOperation(value = "用户在线预约时发送验证码",notes = "用户在线预约时发送验证码")
    @ApiImplicitParam(name = "telephone",value = "手机号",required = true,dataType = "String")
    @GetMapping("/send4Order")
    public Result send4Order(String telephone){
        //为用户随机生成一个6位验证码
        String validateCode = ValidateCodeUtils.generateValidateCode(6).toString();
        //调用阿里云短信服务为用户发送验证码
        try {
            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE,telephone,validateCode);
        } catch (ClientException e) {
            e.printStackTrace();
            //短信发送失败
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
        }

        //将验证码保存到redis中，设置有效期为5分钟
        redisTemplate.opsForValue().set(telephone+ RedisConstant.SENDTYPE_ORDER,validateCode,300L, TimeUnit.SECONDS);
        return new Result(true,MessageConstant.SEND_VALIDATECODE_SUCCESS);
    }

    //用户手机快速登录时发送验证码
    @ApiOperation(value = "用户手机快速登录时发送验证码",notes = "用户手机快速登录时发送验证码")
    @ApiImplicitParam(name = "telephone",value = "手机号",required = true,dataType = "String")
    @GetMapping("/send4Login")
    public Result send4Login(String telephone){
        //为用户随机生成一个6位验证码
        String validateCode = ValidateCodeUtils.generateValidateCode(6).toString();
        //调用阿里云短信服务为用户发送验证码
        try {
            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE,telephone,validateCode);
        } catch (ClientException e) {
            e.printStackTrace();
            //短信发送失败
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
        }
        //将验证码保存到redis中，设置有效期为5分钟
        redisTemplate.opsForValue().set(telephone+ RedisConstant.SENDTYPE_LOGIN,validateCode,300L, TimeUnit.SECONDS);
        return new Result(true,MessageConstant.SEND_VALIDATECODE_SUCCESS);
    }
}
